package com.heima.leetcode.practice;

import java.util.HashMap;
import java.util.HashSet;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 202. 快乐数
 * @date 2025/3/25 21:01
 */
public class E202 {

    /**
     * 方法一：快慢指针
     * @param n 初始值
     * @return 是否是快乐数
     */
    public boolean isHappy1(int n) {
        int slow = n, fast = n;
        while(true){
            slow = next(slow);
            fast = next(next(fast));
            if (slow == 1 || fast == 1) return true;
            if (slow == fast) return false;
        }
    }

    /**
     * 求下一个数
     * @param n 初始值
     * @return 下一个数
     */
    private int next(int n) {
        int result = 0;
        while(n > 0){
            int num = n % 10;
            result += num * num;
            n /= 10;
        }
        return result;
    }

    public boolean isHappy2(int n) {
        HashSet<Integer> hashSet = new HashSet<>();
        hashSet.add(n);
        while(n != 1){
            n = next(n);
            if (hashSet.contains(n)) return false;
            hashSet.add(n);
        }
        return true;
    }
}
